<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        #container {
            width: 300px;
            height: 400px;
            /* border: 1px solid red; */
            margin: 50px auto;
        }
        
        .box {
            width: 300px;
            height: 300px;
            background: skyblue;
        }
    </style>
</head>

<body>
    <div id="container">
        <div class="box"></div>
        <button>开始</button> <button>停止</button>
    </div>
    <script>
        // 获取元素
        let box = $(".box")[0];
        let start = $("button")[0];
        let end = $("button")[1];
        let timer;

        start.onclick = function() {
            timer = setInterval(function() {
                box.style.background = random_color(6);
            }, 1000);
        }

        end.onclick = function() {
            clearInterval(timer);
        }

        function random_color(n) {
            let color_arr = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
            let arr = [];
            for (let i = 0; i < n; i++) {
                let random = Math.floor(Math.random() * 15);
                arr.push(color_arr[random]);
            }
            let sum = "#";
            for (let i = 0; i < arr.length; i++) {
                sum += arr[i];
            }
            return sum;
        }

        function $(select) {
            return document.querySelectorAll(select);
        }
    </script>
</body>

</html>